// License Notification
//======================================================
// Copyright (c) 2010 Channel Intelligence Inc.
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// which accompanies this distribution, and is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// ======================================================




using System;
using System.IO;
using CIP4.Common;

namespace CIP4.Installer
{
    public class SetUpSqlDataProviderType
    {
        private int _ErrorCount;

        public int ErrorCount
        {
            get { return _ErrorCount; }
            set { _ErrorCount = value; }
        }

        readonly LoggerDelegate _logger;

        public SetUpSqlDataProviderType(string databaseName, string host, string location, bool useExisting, LoggerDelegate logger)
        {
            _logger = logger;
            if (string.IsNullOrEmpty(databaseName))
            {
                ErrorMsg("You must provide a database name");
                return;
            }
            if (string.IsNullOrEmpty(location))
            {
                ErrorMsg("You must provide a database location");
                return;
            }
            if (!Directory.Exists(location))
            {
                ErrorMsg(string.Format("The given database location ({0}) does not exist", location));
                return;
            }
            try
            {
                if (!File.Exists(databaseName + ".sql"))
                {
                    if (useExisting)
                    {
                        ErrorMsg(">>>>> Warning - you asked to use an existing .sql file but no existing file was found");
                    }
                }
                else if (!useExisting)
                {
                    int ticks = Environment.TickCount;
                    new FileInfo(databaseName + ".sql").MoveTo(databaseName + ticks + ".sql");
                    InfoMsg(string.Format("Existing sql file as been renamed to {0}{1}.sql - if you want to use this file rename the file back to its original name and run the command with /NewDataProviderUseExistingSqlFile true (or /NewE true)", databaseName, ticks));
                }
                if (!File.Exists(databaseName + ".sql"))
                {
                    if (useExisting)
                        ErrorMsg(">>>>> Warning - you asked to use an existing .sql file but no existing file was found");
                    InfoMsg("Using the default DataProvider.sql file");
                    StreamReader rdr = new StreamReader(GetType().Assembly.GetManifestResourceStream("CIP4.Installer.DataProviderHeader.sql"));
                    string sqlText = rdr.ReadToEnd();
                    rdr.Close();
                    rdr = new StreamReader(GetType().Assembly.GetManifestResourceStream("CIP4.Installer.DataProvider.sql"));
                    sqlText += Environment.NewLine + rdr.ReadToEnd();
                    rdr.Close();
                    StreamWriter wrtr = new StreamWriter(databaseName + ".sql");
                    wrtr.Write(sqlText);
                    wrtr.Close();
                }
                else
                {
                    if (!string.IsNullOrEmpty(location))
                        ErrorMsg(string.Format(">>>> Warning - using existing file - given database location '{0}' will be ignored", location));
                }

                // files are setup - build the database
                {
                    StreamReader rdr = new StreamReader(databaseName + ".sql");
                    string sqlText = rdr.ReadToEnd();
                    rdr.Close();
                    string newText = SqlScriptProcessorType.ProcessSqlScript(sqlText, host, databaseName, location, InfoMsg, ErrorMsg);
                    StreamWriter swrtr = new StreamWriter(databaseName + ".sql");
                    swrtr.Write(newText);
                    swrtr.Close();
                }
            }
            catch (Exception ex)
            {
                ErrorMsg("Unexpected exception in SetUpDataProviderType", ex.ToString());
            }
        }
        public void ErrorMsg(string msg)
        {
            _ErrorCount++;
            _logger(MajorEnum.Error, MinorEnum.Generic, msg, new object[] {} );
        }
        public void ErrorMsg(string msg, string extras)
        {
            _ErrorCount++;
            _logger(MajorEnum.Error, MinorEnum.Generic, msg, new object[] { extras });
        }
        public void InfoMsg(string msg)
        {
            _logger(MajorEnum.Information, MinorEnum.Generic, msg, new object[] { });
        }
    }
}
